// 路由鉴权
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

import pinia from './store/store.ts'
import useUserStore from '@/store/modules/userStore'
import { ElNotification } from 'element-plus'

// 环境变量
import project_setting from '@/project_setting'

const userStore = useUserStore(pinia)

nprogress.configure({ showSpinner: false })
//
const need_permission_route = ['/home', '/screen', '/acl', '/product']

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  document.title = `${project_setting.title}-${to.meta.title}`
  nprogress.start()
  console.log(to, from)
  //   console.log(userStore.token)
  //   去往地址的一级路由
  const firstRoute = '/' + to.path.split('/')[1] // 分割字符串
  const needLoginRoute = need_permission_route.indexOf(firstRoute)
  const TOKEN = userStore.token
  const username = userStore.myUserInfo.name
  //   console.log(firstRoute, needLoginRoute)
  //   console.log(username)
  //   console.log(TOKEN)
  if (TOKEN) {
    // 已登录
    if (firstRoute == '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.getUserInfo()
          //   console.log(username)
          next({ ...to })
        } catch (error) {
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.fullPath } })
          ElNotification({
            type: 'error',
            message: (error as Error).message,
          })
        }
      }
    }
  } else {
    //未登录
    if (needLoginRoute > -1) {
      // 去往的是需要校验的路由
      next({ path: '/login', query: { redirect: to.fullPath } })
    } else {
      next()
    }
  }
})
// 全局后置守卫
router.afterEach(() => {
  //   console.log(to, from)
  nprogress.done()
})
